package tongwentongshu.com.app.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.ext.sns.TIMFriendFutureItem;
import com.tencent.mm.opensdk.utils.Log;
import com.tencent.qcloud.presentation.presenter.ConversationPresenter;
import com.tencent.qcloud.presentation.presenter.FriendshipManagerPresenter;
import com.tencent.qcloud.presentation.viewfeatures.ConversationView;
import com.tencent.qcloud.presentation.viewfeatures.FriendshipMessageView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.activity.MyMessageListActivity;
import tongwentongshu.com.app.activityim.HomeActivity;
import tongwentongshu.com.app.adapter.ConversationAdapter;
import tongwentongshu.com.app.adapter.MessageAdapter;
import tongwentongshu.com.app.bean.AppItem;
import tongwentongshu.com.app.bean.MessageReadBean;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.db.DataKeeper;
import tongwentongshu.com.app.modelim.Conversation;
import tongwentongshu.com.app.modelim.CustomMessage;
import tongwentongshu.com.app.modelim.MessageFactory;
import tongwentongshu.com.app.modelim.NomalConversation;
import tongwentongshu.com.app.network.ResponseSubscriber;
import tongwentongshu.com.app.update.UpdateFractory;
import tongwentongshu.com.app.utils.NetUtils;
import tongwentongshu.com.app.utils.PushUtil;


/**
 * 类描述：
 * 创建人： 史强
 * 创建时间:2017/7/24 13:42
 */
public class ConversationFragment extends Fragment implements ConversationView, FriendshipMessageView {

    private final String TAG = "ConversationFragment";

    private View view;
    private List<Conversation> conversationList = new LinkedList<>();
    private ConversationAdapter adapter;
    private ListView listView;
    private ConversationPresenter presenter;
    private FriendshipManagerPresenter friendshipManagerPresenter;
    private List<String> groupList;
    private FriendshipConversation friendshipConversation;
    //    private GroupManageConversation groupManageConversation;
    @BindView(R.id.tv_title_name)
    TextView title;//title
    @BindView(R.id.title_back)
    ImageView back;//返回键
    private SwipeMenuListView SwipelistView;
    private MessageAdapter Swipeadapter;
    private Map<String, String> map;
//    //通知消息
//    @BindView(R.id.tv_msg_notice_content)
//    TextView noticeContent;
//    @BindView(R.id.tv_msg_notice_time)
//    TextView noticeTime;
//    @BindView(R.id.iv_red_dot_1)
//    ImageView noticeDot;
//    //互动消息
//    @BindView(R.id.tv_msg_interaction_content)
//    TextView interactionContent;
//    @BindView(R.id.tv_msg_interaction_time)
//    TextView interactionTime;
//    @BindView(R.id.iv_red_dot_2)
//    ImageView interactionDot;

    public ConversationFragment() {
        // Required empty public constructor
    }

    MessageReadBean bean;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_conversation, container, false);
            ButterKnife.bind(this, view);
            listView = (ListView) view.findViewById(R.id.list);
            adapter = new ConversationAdapter(getActivity(), R.layout.item_conversation, conversationList);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    conversationList.get(position).navToDetail(getActivity());
//                    if (conversationList.get(position) instanceof GroupManageConversation) {
//                        groupManagerPresenter.getGroupManageLastMessage();
//                    }

                }
            });
            title.setText(R.string.my_message);
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
            bean = (MessageReadBean) DataKeeper.readSerializable(getActivity(), MessageReadBean.class);
            SwipelistView = ((SwipeMenuListView) view.findViewById(R.id.listView));
            setAdapter(bean);
            initSlide();
//            interactionContent.setText(bean.getData().getInteraction_title());
//            interactionTime.setText(bean.getData().getInteraction_time());
//            noticeContent.setText(bean.getData().getSystem_title());
//            noticeTime.setText(bean.getData().getSystem_time());
//            if (bean.getData().getIs_interaction() == 1) {
//                interactionDot.setVisibility(View.VISIBLE);
//            } else {
//                interactionDot.setVisibility(View.GONE);
//            }
//            if (bean.getData().getIs_system() == 1) {
//                noticeDot.setVisibility(View.VISIBLE);
//            } else {
//                noticeDot.setVisibility(View.GONE);
//            }

            friendshipManagerPresenter = new FriendshipManagerPresenter(this);
            presenter = new ConversationPresenter(this);
            presenter.getConversation();
            registerForContextMenu(listView);
        }
        adapter.notifyDataSetChanged();
        return view;

    }

    public void setAdapter(MessageReadBean adapter) {
        Swipeadapter = new MessageAdapter(getActivity(), adapter);
        SwipelistView.setAdapter(Swipeadapter);
        //点击事件一样写
        SwipelistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Bundle nb = new Bundle();
                        nb.putString("type", "1");
                        startActivity(MyMessageListActivity.class, nb);
                        break;
                    case 1:
                        Bundle ib = new Bundle();
                        ib.putString("type", "2");
                        startActivity(MyMessageListActivity.class, ib);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void initSlide() {
        //加入侧滑显示的菜单
        //1.首先实例化SwipeMenuCreator对象
        SwipeMenuCreator creater = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create置顶item
                SwipeMenuItem item1 = new SwipeMenuItem(getActivity());
                // set item background
                item1.setBackground(new ColorDrawable(Color.rgb(27, 136, 236)));
                // set item width
                item1.setWidth(NetUtils.dip2px(getActivity(), 100));
                // set item title
                item1.setTitle("全部已读");
                // set item title fontsize
                item1.setTitleSize(12);
                // set item title font color
                item1.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(item1);

                //同理create删除item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(NetUtils.dip2px(getActivity(), 100));
                // set a icon
                deleteItem.setTitle("全部删除");
                deleteItem.setTitleSize(12);
                deleteItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        SwipelistView.setMenuCreator(creater);

        //2.菜单点击事件
        SwipelistView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        //已读的逻辑
                        Menu("1", position == 0 ? "2" : "1");
                        break;
                    case 1:
                        //删除的逻辑
                        Menu("2", position == 0 ? "2" : "1");
                        break;
                }
                return false;
            }
        });
    }

    public void Menu(String type, String ms_type) {
        map = new ArrayMap<>();
        map.put("token", Cache.getToken());
        map.put("type", type);
        map.put("ms_type", ms_type);
        Log.e("map", map.toString());
        UpdateFractory.getBuild()
                .name("SetallmessageCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<AppItem>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(AppItem myshare, String msg) {
                        intiMessage();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
    }

    public void intiMessage() {
        map = new ArrayMap<>();
        map.put("token", Cache.getToken());
        UpdateFractory.getBuild()
                .name("MessageReadCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<MessageReadBean>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(MessageReadBean bean, String msg) {
                        DataKeeper.keepSerializable(getActivity(), bean);
                        setAdapter(bean);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
    }
//    @OnClick({R.id.rel_msg_interaction, R.id.rel_msg_notice})
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.rel_msg_interaction:
//                Bundle ib = new Bundle();
//                ib.putString("type", "2");
//                startActivity(MyMessageListActivity.class, ib);
//                break;
//            case R.id.rel_msg_notice:
//                Bundle nb = new Bundle();
//                nb.putString("type", "1");
//                startActivity(MyMessageListActivity.class, nb);
//                break;
//        }
//    }

    /**
     * 携带数据页面跳转
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();

        //使用RxJava避免使用Handler导致的内存泄露,使用Handler需要使用静态内部类
        Observable<Long> timer = Observable.timer(1000, TimeUnit.MILLISECONDS);
        timer.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        System.out.println(aLong + "heihei");

                        refresh();
                        PushUtil.getInstance().reset();
                    }
                });
    }


    /**
     * 初始化界面或刷新界面
     *
     * @param conversationList
     */
    @Override
    public void initView(List<TIMConversation> conversationList) {
        this.conversationList.clear();
        groupList = new ArrayList<>();


        for (TIMConversation item : conversationList) {
            switch (item.getType()) {
                case C2C:
                case Group:
                    this.conversationList.add(new NomalConversation(item));
                    groupList.add(item.getPeer());
                    break;
            }
        }
        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    /**
     * 更新最新消息显示
     *
     * @param message 最后一条消息
     */
    @Override
    public void updateMessage(TIMMessage message) {
        if (message == null) {
            adapter.notifyDataSetChanged();
            return;
        }
        if (message.getConversation().getType() == TIMConversationType.System) {
            return;
        }
        if (MessageFactory.getMessage(message) instanceof CustomMessage) return;
        NomalConversation conversation = new NomalConversation(message.getConversation());
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation c = iterator.next();
            if (conversation.equals(c)) {
                conversation = (NomalConversation) c;
                iterator.remove();
                break;
            }
        }
        conversation.setLastMessage(MessageFactory.getMessage(message));
        conversationList.add(conversation);
        Collections.sort(conversationList);
        refresh();
    }

    /**
     * 更新好友关系链消息
     */
    @Override
    public void updateFriendshipMessage() {
        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    /**
     * 删除会话
     *
     * @param identify
     */
    @Override
    public void removeConversation(String identify) {
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation conversation = iterator.next();
            if (conversation.getIdentify() != null && conversation.getIdentify().equals(identify)) {
                iterator.remove();
                adapter.notifyDataSetChanged();
                return;
            }
        }
    }


    /**
     * 刷新
     */
    @Override
    public void refresh() {
        Collections.sort(conversationList);
        adapter.notifyDataSetChanged();
        if (getActivity() instanceof HomeActivity)
            ((HomeActivity) getActivity()).setMsgUnread(getTotalUnreadNum() == 0);
    }


    /**
     * 获取好友关系链管理系统最后一条消息的回调
     *
     * @param message     最后一条消息
     * @param unreadCount 未读数
     */
    @Override
    public void onGetFriendshipLastMessage(TIMFriendFutureItem message, long unreadCount) {
        if (friendshipConversation == null) {
            friendshipConversation = new FriendshipConversation(message);
//            conversationList.add(friendshipConversation);
        } else {
            friendshipConversation.setLastMessage(message);
        }
        friendshipConversation.setUnreadCount(unreadCount);
        Collections.sort(conversationList);
        refresh();
    }

    /**
     * 获取好友关系链管理最后一条系统消息的回调
     *
     * @param message 消息列表
     */
    @Override
    public void onGetFriendshipMessage(List<TIMFriendFutureItem> message) {
        friendshipManagerPresenter.getFriendshipLastMessage();
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        Conversation conversation = conversationList.get(info.position);
        if (conversation instanceof NomalConversation) {
            menu.add(0, 1, Menu.NONE, getString(R.string.conversation_del));
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        NomalConversation conversation = (NomalConversation) conversationList.get(info.position);
        switch (item.getItemId()) {
            case 1:
                if (conversation != null) {
                    if (presenter.delConversation(conversation.getType(), conversation.getIdentify())) {
                        conversationList.remove(conversation);
                        adapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }

    private long getTotalUnreadNum() {
        long num = 0;
        for (Conversation conversation : conversationList) {
            num += conversation.getUnreadNum();
        }
        return num;
    }


}
